<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * Asset Manager
 *
 * Software to automatically manage how assets are delivered on a website
 *
 * @package		Asset Manager
 * @author		Adam Lewis <adam.lewis@bestservedcold.com>
 * @copyright	Copyright (c) 2006 - 2012, Best Served Cold Media Limited.
 * @license		http://bestservedcold.com/license.html
 * @link		http://bestservedcold.com
 * @since		Version 1.0
 * @filesource
 */

// ------------------------------------------------------------------------

/**
 * CDN Amazon Library
 *
 * The Handler library deals with getting the information in and out of the
 * CDN.
 *
 * @package		Asset Manager
 * @subpackage	CDNs
 * @category	Libraries
 * @author  	Adam Lewis <adam.lewis@bestservedcold.com>
 * @since		2012-05-22
 */
require_once(APPPATH.'libraries/asset_manager/Am_cdn.php');
class Am_cdn_amazon extends Am_cdn {

	private $s3;
	private $bucket;
	private $private_key;
	private $secret_key;

	public function __construct($bucket = FALSE)
	{
		parent::__construct();
		log_message('debug', '[CDN_AMAZON] Cdn_amazon loaded');
		require_once(APPPATH.'libraries/asset_manager/am_cdn/am_cdn_amazon/s3.php');
		$this->s3 = new S3();
		$this->bucket = $bucket ? $bucket : get_cdn_bucket();
		$this->s3->setAuth($this->CI->config->item('cdn_access_key', 'asset_manager'),
			$this->CI->config->item('cdn_secret_key', 'asset_manager'));
	}

	public function put_file($file, $content_type)
	{
		$this->create_bucket();
		return $this->s3->putObjectFile($_SERVER['DOCUMENT_ROOT'].'/'.$file, $this->bucket, $file,
			S3::ACL_PUBLIC_READ, array("Cache-Control" => "max-age=315360000",
			"Expires" => gmdate("D, d M Y H:i:s T", strtotime("+5 years"))), $content_type);
	}

	public function check_bucket_exists()
	{
		return $this->CI->config->item('cdn_check_bucket', 'asset_manager') ?
			in_array($this->bucket, $this->s3->listBuckets()) : TRUE;
	}

	public function create_bucket()
	{
		return $this->check_bucket_exists() ? TRUE :
			$this->s3->putBucket($this->bucket, S3::ACL_PUBLIC_READ) ;
	}
}